<?php

namespace api\modules\v1\models;

use Yii;
use api\common\models\Common;
use yii\web\HttpException;
class Shield extends Common
{

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%shield_app}}';
    }


    public function rules()
    {
        return [
            ['type', 'required','message'=>'屏蔽类型不能为空'],
            ['type', 'integer','message'=>'屏蔽类型必须是整数'],
            ['type', 'in', 'range' => [1,2]],

            ['type_id', 'required','message'=>'屏蔽id不能为空'],
            ['type_id', 'integer','message'=>'屏蔽id必须是整数'],
            ['type_id', 'validateTypeId'],

            ['catid', 'integer','message'=>'栏目必须是整数'],
            ['catid', 'default', 'value' => 0]
        ];
    }

    public function attributeLabels()
    {
        return [
            'type' => Yii::t('app', '屏蔽类型'),
            'type_id' => Yii::t('app', '屏蔽id'),
            'catid' => Yii::t('app', '栏目'),
        ];
    }

    public function shield(){
        if ($this->validate()) {
            if(self::findOne(['uid'=>Yii::$app->user->identity->id,'catid'=>$this->catid,'type'=>$this->type,'type_id'=>$this->type_id])){
                throw new HttpException(401,'该屏蔽已经存在!',0);
            }
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }

    public function validateTypeId($attribute, $params)
    {
        $type = $this->type;
        if($type == 1){ //重复、旧闻,内容质量差,不感兴趣此条稿件 直接屏蔽文章
            if(!isset($this->catid) || $this->catid == ''){ //栏目必须
                $this->addError($this->catid,'屏蔽文章栏目必须');
                return false;
            }
            //验证栏目id是否存在
            $this->catid = (int)$this->catid;
            if(!Category::findOne(['catid'=>$this->catid])){
                $this->addError($this->catid,'栏目id:'.$this->catid.'不存在');
                return false;
            }

            //验证文章id是否存在
            $news_model = News::getTable($this->catid);
            $db = \Yii::$app->db;
            if (!$rows = $db->createCommand('SELECT id,catid FROM {{%' . $news_model . '}} where id = ' . $this->type_id)->queryOne()) {
                $this->addError($this->type_id,'文章id:'.$this->type_id.'不存在');
                return false;
            }

            //验证码 文章是否在栏目里面
            if($rows['catid'] != $this->catid){
                $this->addError($this->type_id,'文章id:'.$this->type_id.'与栏目id:'.$this->catid.'不匹配');
                return false;
            }

        }elseif($type ==2 ){ //来源于发稿号 直接屏蔽来源用户
            //验证用户id是否存在
            if(!User::findOne(['id'=>$this->type_id])){
                $this->addError($this->catid,'来源id:'.$this->type_id.'不存在');
                return false;
            }
            $this->catid = 0;
        }

        return true;
    }

}
